const { User, Role } = require('../../model');
const { Op } = require('sequelize');
const Token = require('../../utils/jwt');
// const md5 = require('md5');

// 注册接口
const reg = async (req, res) => {
  console.log('注册');
  // post 通过 req。body  获取传输过来的参数
  const { phone, name, pwd, nickname, age, email, description, role, avatar } = req.body;
  console.log(req.body);
  try {
    const model = await User.findAll({ where: { phone } }); //查询是否存在
    if (model.length) {
      res.send({ msg: '用户已存在', errcode: 1, success: false, data: model });
      return;
    }
    const userCreate = await User.create({ phone, name, pwd, nickname, age, email, description, role, avatar }); // 创建一条记录
    if (!userCreate) {
      res.send({ errcode: 1, msg: '注册失败', success: false });
      return;
    }
    res.send({
      errcode: 0,
      msg: 'ok',
      success: true,
    });
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '注册失败 ' + error, success: false });
  }
};

const login = async (req, res) => {
  console.log('登陆');
  // post 通过 req。body  获取传输过来的参数
  const { phone, pwd } = req.body;
  try {
    const model = await User.findOne({ where: { phone } }); //查询是否存在
    if (model) {
      if (model.phone != phone || model.pwd != pwd) {
        res.send({ errcode: 1, msg: '账号或者密码错误', success: false });
      } else {
        // 登陆成功  根据手机号生成token
        const token = Token.encrypt({ id: model.id }, 60 * 60 * 1000);
        // 生成token
        res.send({ errcode: 0, msg: 'ok', data: { token }, success: true });
      }
    } else {
      res.send({ errcode: 1, msg: '账号不存在，请注册后登陆', success: false });
    }
  } catch (error) {
    console.log('服务错误->登陆失败:', error);
    res.send({ errcode: 1, msg: '登陆失败', success: false });
  }
};

// 通过token 获取用户信息
const getUserInfo = async (req, res) => {
  const {
    headers: { authorization },
  } = req;
  console.log('token', authorization);
  // 获取token
  const token = Token.decrypt(authorization);
  // 解密token
  const { id } = token;

  try {
    let userInfo = await User.findOne({ where: { id: id }, attributes: ['id', 'phone', 'name', 'nickname', 'email', 'avatar', 'age', 'description', 'role'] });
    if (userInfo) {
      console.log('token', token, userInfo);
      res.send({ errcode: 0, msg: '登陆成功', data: userInfo, success: true });
    } else {
      res.send({ errcode: 1, msg: '用户不存在', success: false });
    }
  } catch (error) {
    res.send({ errcode: 1, msg: '登陆失败，token错误' + error, success: false });
  }
};

// 获取用户列表
const getUserList = async (req, res) => {
  console.log('获取用户列表');
  const { pageIndex = 1, pageSize = 10 } = req.body;
  try {
    const model = await User.findAndCountAll({
      where: {
        id: {
          [Op.ne]: 1,
        },
      },
      attributes: { exclude: ['pwd', 'updatedAt'] }, // 不显示字段
      limit: pageSize - 0, // 条数
      offset: (pageIndex - 1) * pageSize, // 偏移量
      order: [['createdAt', 'DESC']],

      // 关联信息查询
      include: [
        {
          model: Role,
          as: 'roleInfo',
          attributes: ['id', 'label', 'desc'],
        },
      ],
    });

    if (model) {
      res.send({ errcode: 0, msg: 'ok', data: model, success: true });
    } else {
      res.send({ errcode: 1, msg: '查询失败', success: false });
    }
  } catch (error) {
    res.send({ errcode: 1, msg: '查询失败: ' + error, success: false });
  }
};

// 更新用户信息
const updateUserInfo = async (req, res) => {
  console.log('更新用户信息');
  const {
    headers: { authorization },
  } = req;
  // 获取token
  const token = Token.decrypt(authorization);
  // 解密token
  const { nickname, name, avatar = '', email, age, description, role } = req.body;
  console.log(token);
  try {
    const roleUser = await User.findOne({ where: { id: token.id } }); //查询修改人是否有权限
    const editUser = await User.findOne({ where: { id: req.body.id } }); // 需要更新的人物
    console.log('role', { roleUser }, 'editUser', { editUser });
    if (roleUser.role === 1) {
      await editUser.update({
        nickname,
        name,
        email,
        avatar,
        age,
        role: role,
        description,
      });
      res.send({ errcode: 0, msg: 'ok', success: true });
    } else {
      res.send({ errcode: 1, msg: roleUser.role === 1 ? '没有权限' : '用户不存在', success: false });
    }
  } catch (error) {
    res.send({ errcode: 1, msg: '网络错误：' + error, success: false });
  }
};

// 删除角色
const deleteUser = async (req, res) => {
  console.log('删除用户');
  const { id } = req.body;
  // 解析token
  const {
    headers: { authorization },
  } = req;
  const token = Token.decrypt(authorization);
  console.log('token', token);
  if (!token.token) {
    res.status(401).send({ errcode: 1, msg: 'token 解析失败', success: false });
    return;
  }
  try {
    const userInfo = await User.findOne({ where: { id: token.id } }); //查询修改人是否有权限
    console.log('role', userInfo);
    // 若是管理员则可以删除
    // 1 为超级管理员权限
    if (userInfo.role === 1 && id) {
      const deleteUser = await User.destroy({ where: { id } });
      if (deleteUser) {
        res.send({ errcode: 0, msg: 'ok', success: true });
      }
    } else {
      res.send({ errcode: 1, msg: '没有权限', success: false });
    }
  } catch (error) {
    res.send({ errcode: 1, msg: '操作失败 ' + error, success: false });
  }
};

module.exports = {
  reg,
  login,
  getUserInfo,
  getUserList,
  updateUserInfo,
  deleteUser,
};
